import React from 'react';
import * as echarts from 'echarts';
import chinaJson from '../assets/china.json'; // 确保你有正确的中国地图JSON文件

interface ChinaMapProps {
  regionData: Record<string, number>;
  language: 'zh' | 'en';
}

const ChinaMap: React.FC<ChinaMapProps> = ({ regionData, language }) => {
  const chartRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (!chartRef.current) return;

    // 注册中国地图
    echarts.registerMap('china', chinaJson as any);

    const chart = echarts.init(chartRef.current);
    
    const option = {
      title: {
        text: language === 'zh' ? '客户地区分布' : 'Customer Distribution',
        left: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 18
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          return `${params.name}: ${params.value || 0} ${language === 'zh' ? '家' : ''}`;
        }
      },
      visualMap: {
        min: 0,
        max: Math.max(...Object.values(regionData), 1),
        text: ['高', '低'],
        realtime: false,
        calculable: true,
        inRange: {
          color: ['#50a3ba', '#eac736', '#d94e5d']
        },
        textStyle: {
          color: '#fff'
        }
      },
      series: [{
        name: language === 'zh' ? '客户数量' : 'Customers',
        type: 'map',
        map: 'china',
        emphasis: {
          label: {
            show: true
          }
        },
        data: Object.entries(regionData).map(([name, value]) => ({
          name,
          value
        })),
        itemStyle: {
          areaColor: '#2c3e50',
          borderColor: '#3498db'
        },
        selectedMode: 'single'
      }]
    };

    chart.setOption(option);

    const handleResize = () => chart.resize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      chart.dispose();
    };
  }, [regionData, language]);

  return <div ref={chartRef} style={{ width: '100%', height: '100%' }} />;
};

export default ChinaMap;